package com.cz.datafetcher.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.cz.datafetcher.entity.search.BaseSearchModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

public abstract class SingleTabControllerBase
        <TObj, Key extends Serializable, Service extends IService<TObj>,Search extends BaseSearchModel> {

    //@Autowired
    //M mapper;

    @Autowired
    protected Service service;

    @PostMapping("/insert")
    @ApiOperation("添加")
    public Key insert(@RequestBody TObj tObj){
        service.save(tObj);
        //int insert = mapper.insert(tObj);
        return getKeyFromObj(tObj);
    }

    @PostMapping("/update")
    @ApiOperation("更新")
    public boolean update(@RequestBody TObj tObj){
        return service.updateById(tObj);
        //int i = mapper.updateById(tObj);
        //return i>0;
    }

    @PostMapping("/delete")
    @ApiOperation("删除")
    public boolean delete(Key id){
        return service.removeById(id);
        //int i = mapper.deleteById(id);
        //return i>0;
    }

    @PostMapping("/deleteByIds")
    @ApiOperation("批量删除,所传id全部不存在返回false，其他返回true")
    public boolean deleteByIds(@RequestBody Collection<Key> ids){
        return service.removeByIds(ids);
    }

    @GetMapping("/all")
    @ApiOperation("查询全部，一般用于下拉菜单")
    public List<TObj> All(){
        return service.list();
    }

    @PostMapping("/search")
    @ApiOperation("条件搜索，一般用于列表展示")
    public IPage<TObj> Search(@RequestBody Search search){
        Page page = new Page(search.getPage(),search.getPagesize());

        QueryWrapper<TObj> qw = buildQueryWrapper(search);

        return service.page(page,qw);
    }

    protected abstract QueryWrapper<TObj> buildQueryWrapper(Search search);

    protected abstract Key getKeyFromObj(TObj tObj);
}
